package com.htwy.core.controller;

import com.htwy.core.config.WebappConfig;
import com.htwy.core.model.Permission;
import com.htwy.ext.BaseController;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;

public class PermissionController extends BaseController<Permission> {

    @Override
    protected Permission dao() {
        return Permission.dao;
    }

    public void tree() {
        renderJson(Ret.ok().set("data",dao().findByIsNotAction(getConditions())));
    }

    @Override
    public boolean beforeSave(Permission entity) {
        if(StrKit.isBlank(entity.getCode())){
            renderJson(Ret.fail().set("msg","编码不能为空,请填写编码!"));
            return false;
        }

        if(dao().countByCodeExcludeId(entity.getCode(),entity.getUuid()) == 0) {
            Permission parent = dao().findById(entity.getParentId());
            if (StrKit.isBlank(entity.getUuid())) {
                entity.setChildrenCount(0);
            }
            if (entity.getSerial() == null) {
                entity.setSerial(getNextSerial(entity.getParentId()));
            }
            return true;
        } else {
            renderJson(Ret.fail().set("msg","已存在相同编码的权限,请修改编码!"));
            return false;
        }

    }

    private Integer getNextSerial(String parentId) {
        Integer maxSerial = dao().getMaxSerialByParentId(parentId);
        return maxSerial != null ? maxSerial + 1 : 1;
    }

    @Override
    public boolean afterSave(Permission entity) {
        dao().updateChildrenCount(entity.getParentId());
        return true;
    }

    @Override
    public void batchDelete() {
        String[] pkArray = getParaValues(dao().getPrimaryKey() + WebappConfig.getConfig().get("idsSuffix", "s"));
        Permission permission = dao().findById(pkArray[0]);
        Integer result = dao().deleteByPks(pkArray);
        dao().updateChildrenCount(permission.getParentId());
        renderJson(Ret.ok().set("data", result));
    }

    public void roleTree() {
        renderJson(Ret.ok().set("data",dao().findRoleTree(getConditions())));
    }
}